import { reqLogin, reqUserInfo, reqLogout } from "@/api/login";
import { getToken, removeToken, setToken } from "@/utils/auth";

const state = () => {
  return {
    token: getToken() || "",
    userInfo: [],
  };
};

const mutations = {
  SET_TOKEN(store, payload) {
    store.token = payload.token;
    setToken(payload.token);
  },
  SET_USERINFO(store, payload) {
    store.userInfo = payload;
  },
  CLEAR_TOKENANDUSERINFO(store) {
    store.token = "";
    store.userInfo = [];
    removeToken();
  },
};
const actions = {
  async getLogin(store, payload) {
    try {
      const { username, password } = payload;
      const result = await reqLogin(username, password);
      store.commit("SET_TOKEN", { token: result.token });
    } catch (error) {
      return Promise.reject(error);
    }
  },
  async getUserInfo(store) {
    try {
      const result = await reqUserInfo();
      store.commit("SET_USERINFO", result);
    } catch (error) {
      return Promise.reject(error);
    }
  },
  async getLogout(store) {
    try {
      const result = await reqLogout();
      store.commit("CLEAR_TOKENANDUSERINFO", { result });
    } catch (error) {
      return Promise.reject(error);
    }
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
